<template>
  <div class="top_list_contaner padd100">
    <el-row :gutter="20">
      <el-col :lg="5">
        <div style="overflow:hidden">
          <el-menu :default-active="menuDefaultActive" class="el-menu-vertical-demo">
            <el-sub-menu :index="index + 1" v-for="(item,index) in teseBang" :key="item.id">
              <template #title>
                <span>{{item.fatherText}}</span>
              </template>
              <el-menu-item :index="index + 1 + '-' + indexs" v-for="(items,indexs) in item.sonText" :key="items.id"
                @click="menuClick(e,items)">
                <div class="menu_left">
                  <img :src="items.coverImgUrl" alt="">
                </div>
                <div class="menu_right text_ellipsis">
                  <span> {{items.name}}</span>
                  <span style="margin-left: 10px;">{{items.updateFrequency}}</span>
                </div>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </div>
      </el-col>
      <el-col :lg="19">
        <div class="music_detail_container">
          <div class="top_music_info">
            <div class="left_music_info_img">
              <img :src="playlist.coverImgUrl" alt="">
            </div>
            <div class="right_music_opeation">
              <div class="r_m_tit">
                {{playlist.name}}
              </div>
              <p class="r_m_time">
                <el-icon>
                  <Timer />
                </el-icon><span>最近更新：{{dayjs(playlist.trackUpdateTime).format('MM月DD日')}}</span>
              </p>
              <div class="r_m_opea">
                <el-button type="primary" :icon="VideoPlay" @click="play">播放</el-button>
                <el-button type="primary" :icon="Plus" @click="addPlayList">添加到播放列表</el-button>
                <el-button type="primary" :icon="FolderAdd" @click="collectionPlayList()">收藏 <span
                    v-if="playlist.subscribedCount>0">({{playlist.subscribedCount}})</span></el-button>
                <el-button :icon="Comment" @click="handleClickScrollToComment">评论 <span
                    v-if="playlist.commentCount>0">({{playlist.commentCount}})</span>
                </el-button>
              </div>
            </div>
          </div>
          <div class="buttom_music_list">
            <div class="top_b_m_tit">
              <div class="left_tit">
                <div>歌曲列表</div>
                <span>{{playlist.trackCount}}首歌</span>
              </div>
              <div class="right_play_count">
                <span>播放：<span>{{playlist.playCount}}</span>次</span>
              </div>
            </div>
            <div>
              <MusicTable :tracks="playlist.tracks" />
            </div>
            <!-- 评论 -->
            <div id="comment">
              <div class="top_b_m_tit" style="margin-top:50px">
                <div class="left_tit">
                  <div>评论</div>
                  <span>共{{playlist.commentCount}}条评论</span>
                </div>
              </div>
              <CommentComponent :id="leftMenuItemId" :playlistLimit="20" :pageNum="pageNum" @getTotal="getTotal">
              </CommentComponent>
              <div class="pageination_center" style="margin-top:40px">
                <el-pagination background layout="prev, pager, next" :total="total" v-show="total > 0"
                  v-model:currentPage="pageNum" :page-size="20" @current-change="handleCurrentChange" />
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  <!-- 登录注册弹窗 -->
  <LoginAndRegister ref="loginAndRegisterRef" />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue"
import CommentComponent from "@/components/Comment/index"
import { Plus, Timer, VideoPlay, Comment, FolderAdd, Pointer } from '@element-plus/icons-vue'
import { getTopList, getPlayList } from "@/api/index";
import dayjs from "dayjs";
import { getPlaylistSubscribe } from "@/api/playlist";
import { ElMessage } from 'element-plus'
import { useRoute } from "vue-router";
import router from "@/router";
import MusicTable from "@/components/MusicTable";
import LoginAndRegister from '@/components/LoginAndRegister/index'
import { loginAndRegisterTypeRef } from "@/types/login";
import { useStore } from "vuex";
const store = useStore();
const route = useRoute()
// 路由参数
const id = route.query.id
const menuDefaultActive = ref<string>('1-0')
const loginAndRegisterRef = ref<loginAndRegisterTypeRef | null>()
interface leftMenu {
  id: number,
  fatherText: string,
  sonText: Array<any>
}
const leftMenu = reactive<Array<leftMenu>>([
  {
    id: 1,
    fatherText: '云音乐特色榜',
    sonText: []
  },
  {
    id: 2,
    fatherText: '全球媒体榜',
    sonText: []
  }
])
// 左侧菜单项id ---> 请求对应评论
const leftMenuItemId = ref<any>(null)
const pageNum = ref(1)
const teseBang = reactive(leftMenu)
const total = ref(0)
// 对应歌单信息列表
let playlist = ref<any>({})
const handleChange = (val: string[]) => {
  console.log(val)
}
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
// 获取左侧菜单栏数据
const getTopListData = async () => {
  const res: any = await getTopList()
  let firstMenu: any[] = []
  res.list.forEach((item: any) => {
    if (item.tags.length <= 0) {
      // 无标签证明是云特色榜
      firstMenu.push(item)
    } else {
      leftMenu[1].sonText.push(item)
    }
  })
  // console.log('firstMenu-------', firstMenu);
  leftMenu[0].sonText = firstMenu.splice(0, 3)
  // console.log(leftMenu);
  leftMenu.forEach((item, index) => {
    item.sonText.forEach((items, indexs) => {
      items.idx = index + 1 + '-' + indexs
    })
  })
  if (id) {
    // 如果路径有id参数默认选中menu组件对应的index
    let ids = Number(id)
    leftMenu.forEach(item => {
      let subObj = item.sonText.find((o: { id: number; }) => o.id === ids)
      if (subObj) {
        // console.log(subObj);
        menuDefaultActive.value = subObj.idx
      }
    })
    // 请求对应数据
    getPlayListData(ids)
  }

}
// 左侧菜单项点击事件
const menuClick = async (e: any, items: any) => {
  getPlayListData(items.id)
  // 更换菜单重置页数
  pageNum.value = 1
  if (id) {
    // 清空路由参数😁
    router.push('/discover/toplist')
  }
}
// 获取右侧列表数据
const getPlayListData = async (id: number) => {
  const res: any = await getPlayList({
    id
  })
  playlist.value = res.playlist
  // console.log(res);
  leftMenuItemId.value = res.playlist.id
}
const handleCurrentChange = (val: number) => {
  pageNum.value = val
}
const getTotal = (val: number) => {
  total.value = val
}
// 播放
const play = () => {
  let list = filterMusicData()
  store.dispatch('playAll', { list });
}
// 添加到播放列表
const addPlayList = () => {
  let list = filterMusicData()
  store.dispatch('addList', { list });
}
// 把需要vip 或者音源不可用的过滤出去
const filterMusicData = ():any[] => {
  let list = playlist.value.tracks.filter((item: any)=>{
    return item.fee != 1 
  })
  return list
}
// 点击评论跳转指定位置
const handleClickScrollToComment = () => {
  document.getElementById('comment')?.scrollIntoView()
}
onMounted(async () => {
  await getTopListData()
  // 默认执行第一个
  if (!id) {
    getPlayListData(leftMenu[0].sonText[0].id)
  }
})
// 收藏歌单
const collectionPlayList = async () => {
  let cookie = localStorage.getItem('cookie')
  if (cookie) {
    try {
      const res: any = await getPlaylistSubscribe({
        t: 1,
        id: leftMenuItemId.value,
        cookie
      })
      ElMessage({
        message: "收藏成功!",
        type: 'success',
        duration: 5000,
      })
    } catch (err: any) {
      console.log(err);
      if (err.code === 501) {
        ElMessage({
          message: "请勿重复收藏!",
          type: 'error',
          duration: 5000,
        })
      }
    } finally {

    }
  } else {
    if (loginAndRegisterRef.value) {
      console.log(loginAndRegisterRef.value.loginVisible);
      loginAndRegisterRef.value.loginVisible = true
      loginAndRegisterRef.value.getQrKeyData()
    }
  }

}
</script>
<style lang="scss" scoped>
.top_list_contaner {
  margin-top: 20px;

  .top_list_left_menu_item {
    display: flex;
    align-items: center;
  }

  .menu_left {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .menu_right {
    font-size: 12px;
    color: #555;
    margin-left: 10px;
    overflow: hidden;
    flex: 1;
  }
}

.music_detail_container {
  padding: 20px;

  .top_music_info {
    display: flex;
    align-items: center;

    .left_music_info_img {
      width: 150px;
      height: 150px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .right_music_opeation {
      color: #333;
      margin-left: 20px;
      flex: 1;

      .r_m_tit {
        font-size: 20px;
      }

      .r_m_time {
        display: flex;
        align-items: center;

        span {
          margin-left: 8px;
        }
      }

      .r_m_opea {
        margin-top: 20px;

        button {
          margin-bottom: 10px;
          margin-left: 0;
          margin-right: 10px;
        }
      }
    }
  }

  .buttom_music_list {
    margin-top: 50px;
  }
}

.top_b_m_tit {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;

  .left_tit {
    color: #333;
    font-size: 20px;
    display: flex;

    span {
      color: #666;
      font-size: 12px;
      margin-top: 10px;
      margin-left: 14px;
    }
  }

  .right_play_count {
    span {
      color: #666;
      font-size: 12px;

      span {
        color: #409eff;
        font-weight: 700;
      }
    }
  }
}

.m_active {
  background: #e6e6e6;
  // .menu_right {
  //   color: #fff !important;
  // }
}

:deep(.el-menu-item.is-active) {
  background: #169af3;

  .menu_right {
    color: #fff !important;
  }
}
</style>
